package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.backend.entity.OrderInfo;
import com.example.backend.mapper.OrderInfoMapper;
import com.example.backend.util.AuthUtil;
import com.example.backend.entity.ProductListing;
import com.example.backend.mapper.AccountMapper;
import com.example.backend.mapper.ProductListingMapper;
import com.example.backend.service.SellerService;
import com.example.backend.util.WeBASEUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.Arrays;

@Slf4j
@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private WeBASEUtils weBASEUtils;

    @Autowired
    private AuthUtil authUtil;

    @Autowired
    protected AccountMapper accountMapper;

    @Autowired
    private ProductListingMapper productListingMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public String register(String username, String passWordF, String passwordS, String qualificationContent, int accountType) {
        return authUtil.register(username, passWordF, passwordS, qualificationContent, accountType);
    }

    @Override
    public String login(String accountId, String password, int accountType) {
        return authUtil.login(accountId, password, accountType);
    }

    @Override
    public String changePassword(String accountId, String oldPassword, String newPassword, int accountType) {
        return authUtil.changePassword(accountId, oldPassword, newPassword, accountType);
    }

    @Override
    public String postQualificationContent(String accountId, String qualificationContent, int accountType) {
        return authUtil.postQualificationContent(accountId, qualificationContent, accountType);
    }

    @Override
    public String postGoodsInfo(Map<String, String> credentials, MultipartFile[] images) {
        try {
            // 保存图片并获取保存路径
            String imagePaths = saveProductImages(images);

            //将数据封装进ProductListing
            ProductListing productListing = new ProductListing();
            productListing.setListingId(authUtil.generatelistID());
            productListing.setProductName(credentials.get("productName"));
            productListing.setProductImages(imagePaths); // 使用保存后的图片路径 (JSON array string)
            productListing.setProductDescription(credentials.get("productDescription"));
            productListing.setUnitPrice(new BigDecimal(credentials.get("unitPrice"))); // 修改为BigDecimal
            productListing.setSellerId(credentials.get("sellerId"));
            productListing.setListingStatus(1); // 修改为Integer
            productListing.setCreatedAt(LocalDateTime.now());
            productListing.setUpdatedAt(LocalDateTime.now());

            // 通过mapper将ProductListing对象插入到数据库中
            int result = productListingMapper.insert(productListing);
            if (result > 0) {
                return "商品信息提交成功";
            } else {
                return "商品信息提交失败";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存商品图片到指定目录
     * @param images 图片文件数组
     * @return 保存后的图片路径字符串（JSON 数组字符串）
     * @throws IOException
     */
    private String saveProductImages(MultipartFile[] images) throws IOException {
        if (images == null || images.length == 0) {
            return "[]";
        }

        List<String> paths = new ArrayList<>();
        // 使用相对路径保存图片
        String uploadDir = new File(System.getProperty("user.dir") + "/src/main/resources/static/img/").getAbsolutePath();

        for (int i = 0; i < images.length; i++) {
            MultipartFile image = images[i];
            if (!image.isEmpty()) {
                // 生成唯一文件名
                String originalFilename = image.getOriginalFilename();
                String extension = originalFilename != null ?
                        originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
                String uniqueFilename = UUID.randomUUID().toString() + extension;

                // 构建保存路径
                String savePath = uploadDir + File.separator + uniqueFilename;
                File dest = new File(savePath);

                // 确保目录存在
                File parentDir = dest.getParentFile();
                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                // 保存文件
                image.transferTo(dest);

                // 添加路径到结果中
                paths.add("/img/" + uniqueFilename);
            }
        }

        // 将列表序列化为 JSON 数组字符串，MySQL JSON 列可接受
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(paths);
        } catch (JsonProcessingException e) {
            // 作为后备，返回手工构造的 JSON
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            for (int i = 0; i < paths.size(); i++) {
                sb.append('"').append(paths.get(i).replace("\"", "\\\"")).append('"');
                if (i < paths.size() - 1) sb.append(',');
            }
            sb.append("]");
            return sb.toString();
        }
    }

    // 如果前端传来的 productImages 不是 JSON 数组字符串（例如逗号分隔），此方法可将其标准化为 JSON 数组字符串
    private String normalizeToJsonArray(String imagesValue) {
        if (imagesValue == null || imagesValue.trim().isEmpty()) return "[]";
        String trimmed = imagesValue.trim();
        if (trimmed.startsWith("[")) return trimmed; // 已是 JSON
        // 以逗号拆分并去重与修正
        String[] parts = trimmed.split(",");
        List<String> list = new ArrayList<>();
        for (String p : parts) {
            String t = p.trim();
            if (!t.isEmpty()) list.add(t);
        }
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            return "[]";
        }
    }

    @Override
    public String updateGoodsInfo(Map<String, String> credentials, MultipartFile[] images) {
        try {
            String sellerId = credentials.get("listingId");
            QueryWrapper<ProductListing> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("listing_Id", sellerId);
            ProductListing oldProductListing = productListingMapper.selectOne(queryWrapper);
            if (oldProductListing == null) {
                return "商品信息不存在";
            }

            //商品名
            oldProductListing.setProductName(credentials.get("productName"));

            // 处理图片更新
            if (images != null && images.length > 0) {
                String imagePaths = saveProductImages(images);
                oldProductListing.setProductImages(imagePaths);
            }

            //商品介绍
            oldProductListing.setProductDescription(credentials.get("productDescription"));
            //单价
            oldProductListing.setUnitPrice(new BigDecimal(credentials.get("unitPrice")));
            //上架状态
            oldProductListing.setListingStatus(Integer.parseInt(credentials.get("listingStatus")));
            oldProductListing.setUpdatedAt(LocalDateTime.now());

            int result = productListingMapper.update(oldProductListing, queryWrapper);
            if (result > 0) {
                return "商品更新成功";
            }
            return "商品更新失败";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //展示已上架的商品信息
    @Override
    public List<ProductListing> getAvailableProducts(Map<String, String> credentials){
        String sellerId = credentials.get("sellerId");
        QueryWrapper<ProductListing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seller_id", sellerId);
        List<ProductListing> productListing =productListingMapper.selectList(queryWrapper);
        return productListing;
    }



    @Override
    public String deleteGoodsInfo(Map<String, String> credentials) {
        try {
            String listingId = credentials.get("listingId");
            String sellerId = credentials.get("sellerId");

            // 创建查询条件：根据listingId和sellerId查找商品
            QueryWrapper<ProductListing> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("listing_id", listingId);
            queryWrapper.eq("seller_id", sellerId);

            // 检查商品是否存在
            ProductListing productListing = productListingMapper.selectOne(queryWrapper);
            if (productListing == null) {
                return "商品信息不存在";
            }

            // 删除商品
            int result = productListingMapper.delete(queryWrapper);
            if (result > 0) {
                return "商品删除成功";
            }
            return "商品删除失败";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //买家方要提供：交易单号，商品名称，商品数量，商品单价，商品总金额（在后端中计算）卖家账号，买家账号，交易状态，收货地址，交易方式，成交时间
    //卖家补充：商品批次ID，物流单号
    //卖家传入：交易单号，商品名称，商品数量，商品单价，商品总金额（在后端中计算）卖家账号，买家账号，交易状态，收货地址，交易方式，成交时间
    @Override
    public String deliverGoods(Map<String, String> credentials) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transaction_id", credentials.get("transactionId"));
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if (orderInfo == null) {
            return "订单不存在";
        }
        orderInfo.setBatchId(credentials.get("batchId")); // 修改设置批次ID的逻辑
        orderInfo.setLogisticsId(credentials.get("logisticsId"));
        orderInfo.setDeliverTime(LocalDateTime.now());
        orderInfo.setOrderStatus("shipped"); // 更新订单状态为已发货
        orderInfoMapper.update(orderInfo, queryWrapper);
        try {
            //数据上链(交易单号、商品批次ID、商品名称、卖家/买家&第三方账号、物流单号、交易总金额)
            List<Object> param = new ArrayList<>();
            param.add(orderInfo.getTransactionId());
            param.add(credentials.get("batchId"));
            param.add(orderInfo.getProductName());
            param.add(orderInfo.getSellerId());
            param.add(orderInfo.getBuyerId());
            param.add(credentials.get("logisticsId"));
            param.add(orderInfo.getTotalAmount());
            param.add(0);
            weBASEUtils.funcPost("OrderModule","createOrder",param);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            return "发货成功";
        }
    }

    @Override
    public ResponseEntity<?> showBuyerOrderInfo(String accountId) {


        // 创建查询条件
                QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seller_id", accountId);
        List<OrderInfo> orderInfos = orderInfoMapper.selectList(queryWrapper);

        // 查询并返回结果
        return ResponseEntity.ok().body(orderInfos);
    }


}

